package com.pawernode.service;

import com.pawernode.config.MyReturnCallBack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 消息服务类，负责发送消息到RabbitMQ
 */
@Service
@Slf4j
public class MessageService {

    // 注入RabbitTemplate用于发送消息
    @Resource
    private RabbitTemplate rabbitTemplate;
    // 注入自定义的返回回调接口
    @Resource
    private MyReturnCallBack myReturnCallBack;

    /**
     * 初始化方法，设置RabbitTemplate的回调接口
     */
    @PostConstruct
    public void init() {
        rabbitTemplate.setReturnsCallback(myReturnCallBack); // 设置回调
    }

    /**
     * 发送消息到RabbitMQ
     */
    public void sendMsg() {
        // 创建消息，内容为"hello rabbitmq"
        Message message = MessageBuilder.withBody("hello rabbitmq".getBytes())
                .build();
        // 发送消息到指定的exchange和routing key
        rabbitTemplate.convertAndSend("exchange.return.1", "info12", message);
        // 记录日志，消息发送完毕
        log.info("消息发送完毕，发送时间为：{}", new Date());
    }
}
